<?php

class UserController extends Controller
{
    public function actionIndex()
    {
        $this->render('index');
    }

    public function actionGetdata(){

        $page = $_REQUEST['page'];
        $rows = $_REQUEST['rows'];
        $start = ($page-1)*$rows;
        $total = $this->connection->createCommand("select count(1) from crm_user where deleted = 0 ")->queryScalar();
        $result = $this->connection->createCommand("select * from crm_user where deleted = 0  limit {$rows} offset {$start}")->queryAll();

        $data = Array();
        $data['total'] = $total;
        $data['rows'] = $result;

        echo json_encode($data);
    }

    public function actionShowedit(){

        $user_id = $_REQUEST['user_id'];

        $user = null;
        if($user_id==0){
            //新增
        }else{
            //编辑
            $user = $this->connection->createCommand("select * from crm_user where user_id = :user_id")->bindParam(':user_id',$user_id,PDO::PARAM_INT)->queryRow();
        }

        $this->render('showedit',['user'=>$user]);
    }

    public function actionSavedata(){

        $user_id = $_REQUEST['user_id'];
        $username = $_REQUEST['username'];
        $realname = $_REQUEST['realname'];

        if($user_id!=null){

        }else{
            //新增
            $this->connection->createCommand("insert into crm_user (username,realname) values (:username,:realname)")
                ->bindParam(':username',$username,PDO::PARAM_STR)
                ->bindParam(':realname',$realname,PDO::PARAM_STR)
                ->execute();
        }

        //角色进行更新
        $roles = $_REQUEST['roles'];

        //清理权限
        $this->connection->createCommand("delete from sys_authassignment where userid = :userid")->bindParam(':userid',$username,PDO::PARAM_STR)->execute();

        //权限赋权限
        $auth = Yii::app()->authManager;
        foreach($roles as $r){
            $auth->assign($r,$username);
        }
    }

    public function actionRemove(){
        $user_id = $_REQUEST['user_id'];
        $this->connection->createCommand("update crm_user set deleted = 1 
where user_id = :user_id")
            ->bindParam(':user_id',$user_id,PDO::PARAM_INT)
            ->execute();
    }

    /**
     * 加载用户的树形结构，全量
     */
    public function actionLoadusertree(){
        $result = $this->connection->createCommand("SELECT USER_ID AS id,realname as text FROM crm_user;")->queryAll();
        echo json_encode($result);
    }
}